package logic

import (
	"context"
	"nove/models/mysql"

	"nove/noverpc/internal/svc"
	"nove/noverpc/noverpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type BookListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBookListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BookListLogic {
	return &BookListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BookListLogic) BookList(in *noverpc.BookListRequest) (*noverpc.BookListResponse, error) {
	// todo: add your logic here and delete this line
	offset := (in.Page - 1) * in.Size
	var book []mysql.Book
	var count int64
	mysql.DB.Model(&mysql.Book{}).Count(&count)
	query := mysql.DB.Debug().Model(&mysql.Book{})
	if in.Kind != "" {
		query = query.Where("kind like ?", "%"+in.Kind+"%")
	}
	if in.Name != "" {
		query = query.Where("name like ?", "%"+in.Name+"%")
	}
	query.Offset(int(offset)).Limit(int(in.Size)).Order("books.created_at desc").Find(&book)
	var bookList []*noverpc.BookList

	for _, bo := range book {
		list := noverpc.BookList{
			Title: bo.Title,
			Kind:  bo.Kind,
			Name:  bo.Name,
			Intro: bo.Intro,
		}
		bookList = append(bookList, &list)
	}
	return &noverpc.BookListResponse{
		List:  bookList,
		Count: count,
	}, nil
}
